package com.SmartCare.common.dto.apiLog;

import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 接口调用日志表
 * </p>
 *
 * @author young
 * @since 2023-10-06
 */

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ApiManageDTO implements Serializable {

    /**
     * 今日接口调用数
     */
    private Integer todayApiTimes;

    /**
     * 昨日接口调用数
     */
    private Integer yesterdayApiTimes;

    /**
     * 总接口调用数
     */
    private Integer totalApiTimes;

    /**
     * 近日调用接口分布
     */
    private Map<String, Integer> apiDistribution;

    /**
     * 近日接口调用数趋势
     */
    private Map<String, Integer> apiTimesTrend;

    /**
     * 构造函数
     *
     * @param list DTO数据集合
     */
    public ApiManageDTO(List<ApiLogDTO> list) {

        // 获取当前日期
        LocalDate today = LocalDate.now();
        LocalDate yesterday = today.minusDays(1);

        // 初始化各个属性
        todayApiTimes = 0;
        yesterdayApiTimes = 0;
        totalApiTimes = 0;
        apiDistribution = new HashMap<>();
        apiTimesTrend = new HashMap<>();

        // 遍历list计算各项数据
        for (ApiLogDTO log : list) {
            int times = log.getTimes();
            LocalDate createDate = log.getCreateDate();
            String descFunction = log.getDescFunction();

            // 计算今日接口调用数
            if (createDate.equals(today)) {
                todayApiTimes += times;
            }

            // 计算昨日接口调用数
            if (createDate.equals(yesterday)) {
                yesterdayApiTimes += times;
            }

            // 计算总接口调用数
            totalApiTimes += times;

            // 计算接口分布
            apiDistribution.put(descFunction, apiDistribution.getOrDefault(descFunction, 0) + times);

            // 计算接口调用数趋势
            String dateKey = createDate.format(DateTimeFormatter.ofPattern("MM.dd"));
            apiTimesTrend.put(dateKey, apiTimesTrend.getOrDefault(dateKey, 0) + times);

        }
        // 限制apiTimesTrend中只存放最近的7个数据
        apiTimesTrend = apiTimesTrend.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByKey().reversed())
                .limit(7)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
    }
}
